import asyncio
import time
from asyncio import coroutine
from threading import Thread

from datetime import datetime


async def production_task():
    i = 1
    while i<3:
        # 将consumption这个协程每秒注册一个到运行在线程中的循环，thread_loop每秒会获得一个一直打印i的无限循环任务
        asyncio.run_coroutine_threadsafe(consumption(i),
                                         thread_loop)  # 注意：run_coroutine_threadsafe 这个方法只能用在运行在线程中的循环事件使用
        await asyncio.sleep(1)  # 必须加await
        i += 1


async def consumption(i):
    y = 1
    while y<5:
        print("我是第{}任务".format(i))
        print(datetime.now())
        await asyncio.sleep(i)
        y+=1

def fu(i):
    print("我是第{}任务".format(i))
    tt = datetime.now()
    print(tt)
    tk = 0.5 if i == 1 else 3
    for u in range(1,10000000):
        bm = 1
    print(f"{datetime.now()}:完成任务{i} {tt}")
    return 'ok'

def yu(i):
    print("我是第{}任务".format(i))
    tt = datetime.now()
    print(tt)
    for u in range(10000):
        bm = 1
    print(f"{datetime.now()}:完成任务{i} {tt}")

async def tak(i):
    coroutine(fu(i))
    # print("我是第{}任务".format(i))
    # tt = datetime.now()
    # print(tt)
    # tk = 0.5 if i == 1 else 3
    # await asyncio.sleep(tk)
    # print(f"{datetime.now()}:完成任务{i}{tt}")

async def main():
    a = None
    b = None
    c = None

    while True:
        # if a is not None:
        #     a.cancel()
        a = asyncio.Task(tak(1))
        b = asyncio.Task(tak(2))
        c = asyncio.Task(tak(3))
        tasks = [a,b,c]
        asyncio.wait(tasks)
        await asyncio.sleep(1)


def start_loop(loop):
    #  运行事件循环， loop以参数的形式传递进来运行
    asyncio.set_event_loop(loop)
    loop.run_forever()


thread_loop = asyncio.new_event_loop()  # 获取一个事件循环
run_loop_thread = Thread(target=start_loop, args=(thread_loop,))  # 将次事件循环运行在一个线程中，防止阻塞当前主线程
run_loop_thread.start()  # 运行线程，同时协程事件循环也会运行

advocate_loop = asyncio.get_event_loop()  # 将生产任务的协程注册到这个循环中
# advocate_loop.run_until_complete(production_task())  # 运行次循
# advocate_loop.run_until_complete(asyncio.wait([tak(1),tak(3)]))  # 运行次循


advocate_loop.run_until_complete(main()) # 运行次循

print('ok')